﻿/// <Summary> 
/// $Author: Nikhil Chinchwade 
/// This file provides methods to populate local data structure containing configuration information related to Azure roles
/// </summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MindTree.PerfWorkbench.Azure.Monitor.Core;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient.Protocol;
using Microsoft.WindowsAzure.StorageClient.Tasks;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.Diagnostics.Management;
using Microsoft.WindowsAzure.Diagnostics;

namespace MindTree.PerfWorkbench.Azure.Monitor.CommandLib
{
    /// <summary>
    ///Azure Command manager class
    /// </summary>
    /// 

    public class AzureCommandMgr
    {                 
        /// <summary>
        /// Load Azure deployment configuration information from Azure deployment
        /// </summary>
        public static void LoadAzureDeploymentConfig()
        {
            DeploymentDiagnosticManager ddm =null;
            try
            {
                ddm = GetAzDeploymentMgr();
            }
            catch(Exception ex)
            {
                throw;
            }

            IEnumerable<string> roles = ddm.GetRoleNames();
            bool temp = false;
            if (roles.Count() <= 0)
            {
                throw new Exception("Error");
            }
            foreach(string role in roles)
            {
                AzureRole newRole = new AzureRole(role);                
                IEnumerable<string> instances = ddm.GetRoleInstanceIdsForRole(role);
                foreach (string roleInstance in instances)
                {           
                    RoleInstanceDiagnosticManager mg = ddm.GetRoleInstanceDiagnosticManager(role,roleInstance);
                    IList<PerformanceCounterConfiguration> pcc = mg.GetCurrentConfiguration().PerformanceCounters.DataSources;
                    AzureRoleInstance inst = new AzureRoleInstance(roleInstance, mg);
                    inst.AppName = "Application";
                    inst.RoleName = role;
                    newRole.Instances.Add(inst);
                    int ind = AzureMonInstanceContext.ConfigCountersets.GetCountersetIndex(pcc);
                    if(!inst.CounterSetIndex.Contains(ind))
                    {
                        inst.CounterSetIndex.Add(ind);
                    }
                    //newRole.CounterSetIndex = AzureMonInstanceContext.ConfigCountersets.GetCountersetIndex(pcc);

                    //if (temp == false)
                    //{
                    //    AzureMonInstanceContext.ConfigCountersets.CtrSets[newRole.CounterSetIndex].Counters.Add(new PerfCounter(null, "Processor", "% User Time", "_Total"));
                    //    temp = true;
                    //}
                }
                AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles.Add(newRole);
                
            }
            foreach (AzureRole role in AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles)
            {
                foreach (AzureRoleInstance instance in role.Instances)
                {
                    foreach (int cntrsetindex in AzureMonInstanceContext.ConfigCountersets.CtrSets.Keys)
                    {
                        if (instance.CounterSetIndex.Contains(cntrsetindex))
                        {
                            instance.IsChecked.Add(true);                           
                        }
                        else
                        {
                            instance.IsChecked.Add(false);                            
                        }
                    }
                }
            }
        }

        public static void ReloadAzureDeploymentConfig()
        {
            DeploymentDiagnosticManager ddm = GetAzDeploymentMgr();
            IEnumerable<string> roles = ddm.GetRoleNames();   
            foreach(string role in roles)
            {
                IEnumerable<AzureRole> rls = from rl in AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles where rl.RoleName==role select rl ;
                if (rls.Count<AzureRole>() <= 0)
                {
                    AzureRole newRole = new AzureRole(role);
                    IEnumerable<string> instances = ddm.GetRoleInstanceIdsForRole(role);
                    foreach (string roleInstance in instances)
                    {
                        newRole.Instances.Add(new AzureRoleInstance(roleInstance, ddm.GetRoleInstanceDiagnosticManager(role, roleInstance)));
                    }
                    AzureMonInstanceContext.AzureApp.AppDeployment[0].Roles.Add(newRole);
                }
                else if(rls.Count<AzureRole>() == 1)
                {
                    
                    //IEnumerable<string> instances = ddm.GetRoleInstanceIdsForRole(role);
                    //foreach (string roleInstance in instances)
                    //{
                    //    newRole.Instances.Add(new AzureRoleInstance(roleInstance, ddm.GetRoleInstanceDiagnosticManager(role, roleInstance)));
                    //}
                    //AzureMonInstanceContext.AzureApp.AppDeployment.Roles.Add(newRole);
                
                }                
            }
        }


        /// <summary>
        /// Get Azure deployemnt diagnostics manager object from given Azure app deployemnt info
        /// </summary>
        /// <returns></returns>
        public static DeploymentDiagnosticManager GetAzDeploymentMgr()
        {
            CloudStorageAccount csa = CloudStorageAccount.Parse(GetAzAppDeploymentString());
            
            DeploymentDiagnosticManager dm = null;
            try
            {
                csa.CreateDeploymentDiagnosticManager(AzureMonInstanceContext.AzureApp.AppConnectionConfig.AppDeploymentId);
                dm = new DeploymentDiagnosticManager(csa, AzureMonInstanceContext.AzureApp.AppConnectionConfig.AppDeploymentId);
                
            }
            catch (Exception ex)
            {
                throw;
            }
            return dm;
            //return new DeploymentDiagnosticManager(csa, "150");            
        }

        /// <summary>
        /// Get Azure deployemnt connection string
        /// </summary>
        /// <returns></returns>
        public static string GetAzAppDeploymentString()
        {
            return "DefaultEndpointsProtocol=https;AccountName=" + AzureMonInstanceContext.AzureApp.AppConnectionConfig.AccountName + ";AccountKey=" + AzureMonInstanceContext.AzureApp.AppConnectionConfig.AccountKey;
            //return "UseDevelopmentStorage=true";
        }
    }
}
